/**
 * Copyright (C)  Gadglet .
 *
 * This file is part of Gadglet
 *
 * Gadglet is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Gadglet is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with Gadglet. If not, see <http://www.gnu.org/licenses/>.
 */

package com.gadglet.gadgets.bookmarks.client;

import com.gadglet.client.gwt.core.GadgletQuery;
import com.gadglet.client.gwt.core.GadgletRequest;
import com.gadglet.client.gwt.core.GadgletResponse;
import com.gadglet.client.gwt.core.ui.ShareWithDialogPanel;
import com.gadglet.client.gwt.ui.ActionLabel;
import com.gadglet.client.gwt.ui.CanvasViewMainPanel;
import com.gadglet.client.gwt.ui.DebugDialogBox;
import com.gadglet.client.gwt.ui.SimpleDialogBox;
import com.gadglet.client.gwt.ui.UIUtils;
import com.gadglet.gadgets.bookmarks.shared.BookMarkType;
import com.gadglet.gadgets.bookmarks.shared.Params;
import com.gadglet.params.ProfileFields;
import com.gadglet.params.ReqActionTypes;
import com.gadglet.params.ReqTypes;
import com.gadglet.params.SortTypes;
import com.google.gwt.event.dom.client.BlurEvent;
import com.google.gwt.event.dom.client.BlurHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.gadgets.client.ContentSection;
import com.google.gwt.gadgets.client.Gadget.ContentType;
import com.google.gwt.gadgets.client.Gadget.InjectContent;
import com.google.gwt.gadgets.client.PreferencesFeature;
import com.google.gwt.gadgets.client.PreferencesProvider;
import com.google.gwt.gadgets.client.io.MethodType;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DisclosurePanel;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HasVerticalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RadioButton;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
/**
 * The Gadget Canvas view 
 * <p>
 * In this view user can:
 * <li> View personal notes
 * <li> Edit profile
 * <li> View your domain users and create friends
 * <li> Add personal notes
 * <li> Delete personal notes
 * <li> Share personal notes
 * <li> Edit/Update Personal notes 
 */
@InjectContent(files = "canvas.html")
@ContentType(type = "html", views = { "canvas" })
public class BookMarksCanvasView extends
ContentSection<BookMarksGadget> {
	private DebugDialogBox debug = null;

	/**
	 *  Query object use to create a request for personal notes.
	 *  ReqTypes.BIZLET_SIGNED will generate url to the domainSignedRequest servlet
	 */
	final GadgletQuery viewBookMarksQry = new GadgletQuery(
			ReqTypes.BIZLET_SIGNED);
	

	/**
	 * Request object used to send a request to the gadget server
	 * and process the results
	 */
	final ViewBookMarks viewBookMarksRequest = new ViewBookMarks(
			viewBookMarksQry);

	/**
	 * Query object used to build "add", "update" and "delete" requests
	 */
	
	final GadgletQuery changeBookMarkQry = new GadgletQuery(
			ReqTypes.BIZLET_SIGNED);
	
	/**
	 * Request Object used to perform "add" and "delete" requests
	 * and process the results
	 */
	
	final GadgletRequest addDeleteBookMark = new ChangeBookMarks(
			changeBookMarkQry);
	
	/**
	 *  Request Object used to perform "update"  requests
	 */

	final GadgletRequest changeBookMarkRequest = new UpdateBookMarks(
			changeBookMarkQry);
	
	
	final Grid results = new Grid();
	protected final HorizontalPanel paging = new HorizontalPanel();

	final Button prevButton = new Button();
	final Button nextButton = new Button();
	final PreferencesFeature  prefsUtils = PreferencesProvider.get();

	final SimpleDialogBox serverMessage = SimpleDialogBox
	.getMesseageDialogBox();
	

	@Override
	public void init(BookMarksGadget gadget) {
		
		results.setCellSpacing(0);
		results.setCellPadding(10);
		
		addDeleteBookMark.setMethodType(MethodType.POST);
		
		debug = DebugDialogBox.getErrorNotifier();

		prevButton.setText(prefsUtils.getMsg("gadgetLabelPrevious"));
		nextButton.setText(prefsUtils.getMsg("gadgetLabelNext"));
	
		final CanvasViewMainPanel mainPanel = new CanvasViewMainPanel();

		final HorizontalPanel addItemPanel = new HorizontalPanel();
		final DisclosurePanel addDisclosurePanel = new DisclosurePanel();
		
		ActionLabel add = new ActionLabel(prefsUtils.getMsg("gadgetLabelAdd"));
		add.setTitle(prefsUtils.getMsg("gadgetLabelAdd"));
	
		
		addDisclosurePanel.setHeader(add);
		
		final VerticalPanel bookMark = new VerticalPanel();
		
		final TextBox bookMarkUrl = new TextBox();
		bookMarkUrl.setValue("http://");
		bookMarkUrl.setWidth("400px");
		final TextBox bookMarkTitle = new TextBox();
		bookMarkTitle.setWidth("400px");
		
		bookMark.add(bookMarkUrl);
		
		bookMark.add(bookMarkTitle);
		

		final VerticalPanel bookMarkType = new VerticalPanel();
		final RadioButton typePrivate = new RadioButton("priorityFilter",
				prefsUtils.getMsg("gadgetLabelHigh"));
		final RadioButton typePublic = new RadioButton("priorityFilter",
				prefsUtils.getMsg("gadgetLabelMedium"));
		
		typePrivate.setValue(true);
		
		bookMarkType.add(typePrivate);
		bookMarkType.add(typePublic);
		

		final Button saveButton = new Button(
				prefsUtils.getMsg("gadgetLabelSave"));


		addItemPanel.setVerticalAlignment(HasVerticalAlignment.ALIGN_BOTTOM);
		addItemPanel.add(bookMark);

		addItemPanel.add(new HTML("&nbsp;"));
		addItemPanel.add(saveButton);

		addDisclosurePanel.add(addItemPanel);


		mainPanel.add(addDisclosurePanel);

	

		mainPanel.add(results);

		RootPanel.get().add(mainPanel.getGadgetPanel());

		saveButton.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				changeBookMarkQry.setRequestAction(ReqActionTypes.ADD);
				changeBookMarkQry.clearParamList();
				
				
				String bookMarkType = "";
				if (typePrivate.getValue())
					bookMarkType = BookMarkType.PRIVATE.toString();
				else if (typePublic.getValue())
					bookMarkType = BookMarkType.PUBLIC.toString();
				else
					bookMarkType = BookMarkType.PRIVATE.toString();

				changeBookMarkQry.addParam(Params.BOOKMARK_TYPE.getParamName(),
						bookMarkType);
				changeBookMarkQry.addParam(Params.BOOKMARK_URL.getParamName(),
						bookMarkUrl.getValue());
				changeBookMarkQry.addParam(Params.BOOKMARK_TITLE.getParamName(),
						bookMarkTitle.getValue());

				addDeleteBookMark.makeRequest();
				bookMarkUrl.setValue("http://");
				bookMarkTitle.setValue("");

			}
		});

		viewBookMarksQry.setRequestAction(ReqActionTypes.VIEW);
		viewBookMarksQry.addSortBy("creation", SortTypes.ASC);
		viewBookMarksQry
		.setReturnField("personalNotesMessage,creation");
		viewBookMarksQry.setStartItemsFrom(0);
		viewBookMarksQry.setItemsNum(20);
		viewBookMarksRequest.makeRequest();

		prevButton.setVisible(false);
		prevButton.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				viewBookMarksQry.setStartItemsFrom(viewBookMarksQry
						.getStartFrom() - viewBookMarksQry.getItemNum());
				viewBookMarksRequest.makeRequest();

			}

		});
		paging.add(prevButton);

		nextButton.setVisible(false);
		nextButton.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				viewBookMarksQry.setStartItemsFrom(viewBookMarksQry
						.getStartFrom() + viewBookMarksQry.getItemNum());
				viewBookMarksRequest.makeRequest();

			}

		});
		paging.add(nextButton);

	}

	public class ViewBookMarks extends GadgletRequest {
		GadgletResponse jResponse;

		ViewBookMarks(GadgletQuery req) {
			super(req);

		}

		@Override
		protected void processResults(GadgletResponse data) {
			jResponse = data;

			results.resize(0, 4);
			results.clear();
			
			if (jResponse.isSuccessful() && jResponse.getRootItemsNum()>0) {
				results.resize(1, 4);

				
				int index;
				String rowStyle = null;
				
				 
				String href;
				
				
				for (index = 0; index < jResponse.getRootItemsNum(); index++) {
					final Anchor link ;
				/* remove line style
					if (index%2==0)
						rowStyle = "gridRowShadow";
					else
						rowStyle = "gridRowNoShadow";
					results.getRowFormatter().setStyleName(index, rowStyle);
					
				 */
					
					href  = data.getStringItemValue(
							Params.BOOKMARK_URL.getParamName(), index);
					link = new Anchor(); 
					
					if(!href.startsWith("http:") && !href.startsWith("https:") && !href.startsWith("ftp:"))	
						href = "http://"+href;
					
					link.setHref(href);
					
					link.setText(data.getStringItemValue(
							Params.BOOKMARK_TITLE.getParamName(), index));
					link.setTarget("_blank");
					
								
					
					final String noteId = jResponse.getItemKeyValue(index);
					
				
					VerticalPanel bookMarkItem= new VerticalPanel();
					bookMarkItem.add(link);
					
					final TextBox bookMarkUrlEdit = new TextBox();
					final TextBox bookMarkTitleEdit = new TextBox();
					
					if(data.isUpdatePermitted(index)){
						bookMarkUrlEdit.setWidth("500px");
						bookMarkUrlEdit.setVisible(false);
						bookMarkUrlEdit.setText(jResponse.getStringItemValue(
								Params.BOOKMARK_URL.getParamName(), index));
						bookMarkItem.add(bookMarkUrlEdit);
										
						
						bookMarkTitleEdit.setWidth("500px");
						bookMarkTitleEdit.setVisible(false);
						bookMarkTitleEdit.setText(jResponse.getStringItemValue(
								Params.BOOKMARK_TITLE.getParamName(), index));
						bookMarkItem.add(bookMarkTitleEdit);
						
			
						
						bookMarkUrlEdit.addBlurHandler(new BlurHandler(){
							@Override
							public void onBlur(BlurEvent event) {
								// ignore empty
								if(bookMarkUrlEdit.getText().length()==0){
									bookMarkUrlEdit.setVisible(false);
									bookMarkTitleEdit.setVisible(false);
									link.setVisible(true);
									bookMarkUrlEdit.setText(link.getHref());
								}
								else
								{
									bookMarkUrlEdit.setVisible(false);
									bookMarkTitleEdit.setVisible(false);
									link.setHref(bookMarkUrlEdit.getText());
									link.setVisible(true);
									
									changeBookMarkQry.clearParamList();
									
									changeBookMarkQry
									.setRequestAction(ReqActionTypes.UPDATE);
									
									changeBookMarkQry
									.setRequestItemkey(noteId);
											
									changeBookMarkQry.addParam(Params.BOOKMARK_TITLE.getParamName(),
											bookMarkTitleEdit.getText());
									
									changeBookMarkQry.addParam(Params.BOOKMARK_URL.getParamName(),
											bookMarkUrlEdit.getText());
									
									changeBookMarkRequest.makeRequest();
								}
								
								
						}});
						
						bookMarkTitleEdit.addBlurHandler(new BlurHandler(){
							@Override
							public void onBlur(BlurEvent event) {
								// ignore empty
								if(bookMarkTitleEdit.getText().trim().length()==0){
									bookMarkUrlEdit.setVisible(false);
									bookMarkTitleEdit.setVisible(false);
									link.setVisible(true);
									bookMarkTitleEdit.setText(link.getText());
								}
								else
								{
									bookMarkUrlEdit.setVisible(false);
									bookMarkTitleEdit.setVisible(false);
									link.setText(bookMarkTitleEdit.getText());
									link.setVisible(true);
									
									changeBookMarkQry.clearParamList();
									
									changeBookMarkQry
									.setRequestAction(ReqActionTypes.UPDATE);
									
									changeBookMarkQry
									.setRequestItemkey(noteId);
											
									changeBookMarkQry.addParam(Params.BOOKMARK_TITLE.getParamName(),
											bookMarkTitleEdit.getText());
									
									changeBookMarkQry.addParam(Params.BOOKMARK_URL.getParamName(),
											bookMarkUrlEdit.getText());
									
									changeBookMarkRequest.makeRequest();
								}
								
								
						}});
						
						final ActionLabel edit = new ActionLabel(prefsUtils.getMsg("gadgetLabelEdit"));
						
						
						edit.setTitle(prefsUtils.getMsg("gadgetLabelEdit"));
						
						edit.addClickHandler(new ClickHandler() {
							@Override
							public void onClick(ClickEvent event) {
							edit.mouseOff();
							link.setVisible(false);
							bookMarkUrlEdit.setVisible(true);
							bookMarkTitleEdit.setVisible(true);

							}

						});
											
					
						
						results.setWidget(index, 1, edit);
					}
					
					results.setWidget(index, 0, bookMarkItem);
										
					final ActionLabel deleteLabel = new ActionLabel(prefsUtils.getMsg("gadgetLabelDelete"));
					
					deleteLabel.setItemId(jResponse.getItemKeyValue(index));
					
					if(data.isDeletePermitted(index)){
				
					
	
						deleteLabel.addClickHandler(new ClickHandler() {
							@Override
							public void onClick(ClickEvent event) {
								changeBookMarkQry.clearParamList();
								changeBookMarkQry
								.setRequestAction(ReqActionTypes.DELETE);
								changeBookMarkQry
								.setRequestItemkey(noteId);
								addDeleteBookMark.makeRequest();
	
							}
	
						});
						
					}
					else{
						// delete: "hide" sharing 
						
						deleteLabel.addClickHandler(new ClickHandler() {
							@Override
							public void onClick(ClickEvent event) {
								deleteLabel.mouseOff();
								changeBookMarkQry.clearParamList();
								
								changeBookMarkQry
								.setRequestAction(ReqActionTypes.DELETE);
								changeBookMarkQry.setCustomtContentName("sharing");
								changeBookMarkQry
								.setRequestItemkey(noteId);
								addDeleteBookMark.makeRequest();
								changeBookMarkQry.setCustomtContentName(null);
	
							}
	
						});
					}
				
				results.setWidget(index, 2, deleteLabel);
					
				if(data.isSharePermitted(index)){
					
											
						final ActionLabel shareWithLabel = new ActionLabel(prefsUtils.getMsg("gadgetLabelShare"));
					
						
						shareWithLabel.addClickHandler(new ClickHandler() {
							
							public void onClick(ClickEvent event) {
								shareWithLabel.mouseOff();
								ShareWithDialogPanel panel = ShareWithDialogPanel.getShareWithDialogPanel();
								panel.showShareWithDialogPanel(noteId,bookMarkTitleEdit.getText());

							}

						});
						
						
						results.setWidget(index, 3, shareWithLabel);
					}
				else{
					String nick = data.getStringItemValue(ProfileFields.PROFILE_NICKNAME.getParamName(),index);
					String photo = data.getStringItemValue(ProfileFields.PROFILE_THUMBNAILURL.getParamName(),index);
					
					HorizontalPanel profile = new HorizontalPanel();
					profile.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE);
					if(nick!=null)
						if(nick!=null){								
							profile.add(new HTML(prefsUtils.getMsg("gadgetLabelSharedBy")+":"));
							profile.add(UIUtils.getSpace());
							profile.add(new Label(nick));

						}
					if(photo!=null && !photo.isEmpty()){
						profile.add(UIUtils.getSpace());
						Image photoImg = new Image(photo);
						photoImg.setPixelSize(40, 40);
						profile.add(photoImg);
						
					}
					
					results.setWidget(index, 3, profile);
					
				}
					
					
					results.resize(index + 3, 4);

				}
				

				if (viewBookMarksQry.getStartFrom() > 0)
					prevButton.setVisible(true);
				else
					prevButton.setVisible(false);

				if (jResponse.hasMoreItems())
					nextButton.setVisible(true);
				else
					nextButton.setVisible(false);

				results.setWidget(index, 0, paging);

			}

		}
	}

	public class ChangeBookMarks extends GadgletRequest {
		ChangeBookMarks(GadgletQuery req) {
			super(req);
		}

		@Override
		protected void processResults(GadgletResponse data) {
			GadgletResponse jResponse = data;

			if (jResponse.isSuccessful()) {
				// reffresh
				viewBookMarksRequest.makeRequest();
			} else {

				serverMessage
				.showError(prefsUtils.getMsg(jResponse.getError()));
			}

		}
	}
	
	public class UpdateBookMarks extends GadgletRequest {
		UpdateBookMarks(GadgletQuery req) {
			super(req);
		}

		@Override
		protected void processResults(GadgletResponse data) {
						
			GadgletResponse jResponse = data;

			if (jResponse.isSuccessful()) {
				// do nothing
			} else {

				serverMessage
				.showError(prefsUtils.getMsg(jResponse.getError()));
			}

		}
	}

}
